<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class User extends BIT_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -  
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in 
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see http://codeigniter.com/user_guide/general/urls.html
	 */
	public function __construct()
	{
		parent::__construct();
		$this->header_views = array('common/header');
		$this->footer_views = array('common/footer');

		$sliderdata = array('products' => $this->produkter->getSliderProducts());	
		$this->view_data['slider_html'] = $this->load->view('pages/slider', $sliderdata, TRUE);
		$this->view_data['widgets'] = array();
	}

	private function isloggedin(){return (isset($this->session->userdata) && $this->session->userdata('loggedin')===TRUE);}

	public function login(){
	
		# Widgets
		$this->view_data['widgets'] = array($this->load->view('widgets/loginwidget', null, TRUE));

		# load login form from auth
		$this->view_data['login_form'] = $this->load->view('auth/login_form.php', null, TRUE);

		# Handle post data upon login
		$this->v('pages/customer_login');
	}


	public function logout(){
		$this->load->library('tank_auth');
		
		$this->tank_auth->logout();
		redirect('/', 'refresh');
	}

	public function customer_settings(){
		# Menu
		$this->getMenuWidget();

		# These are settings..u know
		$this->v('pages/customer_settings');

	}
	
	public function current_orders() {
		$this->load->model('produkter');
		$this->load->library('cart_handler');
		$orders = $this->cart_handler->get_contents();
		$current_orders = array();
		foreach($orders as $order)
		{
			$current_order = current($this->produkter->findByField(array('id' => str_replace('prod_', '', $order['id']))));
			$current_order->quantity = $order['qty'];
			$current_orders[] = $current_order;
		}

		$this->view_data['current_orders'] = $current_orders;
		$this->v('pages/current_orders');
	}

	# Logged-in homepage
	public function customer_home(){
		# Menu 
		$this->getMenuWidget();

		# Gather information about recent orders and display
		# #### TIPS ####
		# Du mixar models med controllers === NO GOODIE
		# Titta 'public function current' i denna fil
		$this->view_data['orders'] = $this->db->where('email', $this->session->userdata('email') )->order_by('datum','DESC')->get('kunder_order')->result();

		# Display page
		$this->v('pages/customer_home');
	}

	private function getMenuWidget(){
		# Get page , for css stuff and stuff
		$page = $this->uri->uri_string;

		# Menu css
		$data = array(
			'mnu_settings_css' => ($page == "settings" ? "active" : ""),
			'mnu_order_css' => ($page == "orders" || $page == "kundsidor" ? "active" : "")
		);			

		# Menu widget
		$this->view_data['widgets'] = array( $this->load->view('widgets/customer_menu', $data, TRUE) );	
	}


	private function validate_registration(){

		# Rules
		$this->load->helper(array('form', 'url'));
		$this->load->library('form_validation');
		$form_rules = array(
			array(
				'field' => 'firstname',
				'label' => 'Förnamn',
				'rules' => 'trim|required'
			),
			array(
				'field' => 'lastname',
				'label' => 'Efternamn',
				'rules' => 'trim|required'
			),
			array(
				'field' => 'address',
				'label' => 'Adress',
				'rules' => 'trim|required'
			),
			array(
				'field' => 'postnr',
				'label' => 'Postnr.',
				'rules' => 'trim|required'
			),
			array(
				'field' => 'email',
				'label' => 'Epost',
				'rules' => 'trim|required|valid_email'
			),
			array(
				'field' => 'password',
				'label' => 'Lösenord',
				'rules' => 'trim|required|min_length[4]'
			),
			array(
				'field' => 'passwordrepeat',
				'label' => 'Repetera lösenord',
				'rules' => 'trim|required|matches[password]'
			)
		);

		# Messages
		$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
		$this->form_validation->set_message('valid_email','Epostadressen är inte giltig.');
		$this->form_validation->set_message('required','Du måste fylla i fältet %s.');
		$this->form_validation->set_message('min_length','Lösenordet är minst 4 tecken.');
		$this->form_validation->set_message('matches','%s måste matcha %s');

		$this->form_validation->set_rules($form_rules);
		

		# Validate 
		if($this->form_validation->run() == TRUE) {
			# Add user to database
			
			$this->users->addUser();
			$email = $this->input->post('email');
			$passw = $this->input->post('password');

			# Add to newsletter list
			if( $this->db->where('mail',$email)->count_all_results('mail_adresser') === 0 ) {
				# Update database with email address
				$this->db->insert('mail_adresser', array('mail' => $email));
			}
			
			# Login user
			$this->doLogin( $email, $password );
		
			# Show startpage
			$this->customer_home();
		}
		else {
			# Do nothing at all, let the regular page load
			$this->v('pages/customer_login');
		}
	}

	private function validate_login() {
		# Rules
		$this->load->helper(array('form', 'url'));
		$this->load->library('form_validation');
		$form_rules = array(
			array(
				'field' => 'email',
				'label' => 'Epost',
				'rules' => 'trim|required|valid_email'
			),
			array(
				'field' => 'password',
				'label' => 'Lösenord',
				'rules' => 'trim|required|min_length[4]'
			)
		);

		# Messages
		$this->form_validation->set_message('valid_email','Epostadressen är inte giltig');
		$this->form_validation->set_message('required','Du måste fylla i fältet');
		$this->form_validation->set_message('min_length','Lösenordet är minst 5 tecken...');

		$this->form_validation->set_rules($form_rules);
		

		# Validate 
		if($this->form_validation->run() == TRUE) {

			$email = $this->input->post('email');
			$password = md5($this->input->post('password'));
			
			if( $this->doLogin() ){		

				# Show startpage
				$this->customer_home();
			}
			else
			{
				# Handle post data upon login
				$this->v('pages/customer_login');
			}
		}
		else{
			# Handle post data upon login
			$this->v('pages/customer_login');
		}
	}

	// Tries to login user
	// returns boolean
	private function doLogin( $email, $password ){
		$user = $this->db->get_where('users', array('email'=>$email,'password'=>$password))->result();
			
		if(count($user) > 0) {

			$this->session->set_userdata(array(
				'email'=>$user[0]->email,
				'userid'=>$user[0]->id,
				'loggedin'=>TRUE
				)
			);

			return true;
		}
		else {
			return false;
		}
	}
}